/**    
 * @{#} ChongzhiActivity.java Create on 2014-6-10 下午1:35:57    
 *          
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.smiier.skin;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import cn.o.app.json.JsonUtil;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.pay.ali.AlipayListener;
import cn.o.app.pay.ali.AlipayTask;
import cn.o.app.ui.OAlert;
import cn.o.app.ui.OAlert.OAlertListener;
import cn.skinapp.R;

import com.evan.common.share.ShareWXUtils;
import com.evan.common.utils.DeviceUtility;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.net.AccountRechargeApplyTask;
import com.smiier.skin.net.AccountRechargeApplyTask.AccountRechargeApplyRequest;
import com.smiier.skin.net.AccountRechargeApplyTask.AccountRechargeApplyResponse;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

public class ChongzhiActivity extends BasicActivity {

	private TextView text_tip;
	private TextView edit_money;
	protected TextView btn_pay_wechat;
	protected TextView btn_pay_ali;

	public static int CODE = -100001;

	protected boolean mCostFixed = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chongzhi);

		init();
		setNavTitle("账户充值");
		Intent i = getIntent();

		text_tip = (TextView) findViewById(R.id.text_tip);
		edit_money = (TextView) findViewById(R.id.edit_money);
		btn_pay_ali = (TextView) findViewById(R.id.btn_pay_ali);
		btn_pay_wechat = (TextView) findViewById(R.id.btn_pay_wechat);

		CommonUtility.showKeyboard(edit_money);

		double cost = i.getDoubleExtra("Cost_Recharge", 0.0);
		if (!CommonUtility.isNull(cost)) {
			mCostFixed = true;
			text_tip.setVisibility(View.INVISIBLE);
			edit_money.setEnabled(false);
			edit_money.setText(cost + "");
		}
	}

	protected void setUIEnabled(boolean enabled) {
		btn_pay_ali.setEnabled(enabled);
		btn_pay_wechat.setEnabled(enabled);
		if (!mCostFixed) {
			edit_money.setEnabled(enabled);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		
//		MobclickAgent.onResume(this);
		
		if (CODE != -100001) {
			String str = "充值失败";
			switch (CODE) {
			case BaseResp.ErrCode.ERR_OK:
				str = "充值成功";
				Intent data = new Intent(Constant.RECEIVER_ACCOUNT_CHONGZHI);
				sendBroadcast(data);
				break;
			}
			OAlert alert = new OAlert(getContext());
			alert.setOK("确认");
			alert.setTitle(str);
			alert.show();
			alert.setListener(new OAlertListener() {

				@Override
				public boolean onOK(OAlert alert) {
					finish();
					return false;
				}

				@Override
				public boolean onCancel(OAlert alert) {
					return false;
				}
			});

		}
	}

	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.btn_left) {
			finish();
		} else if (id == R.id.btn_pay_wechat) {
			String money = edit_money.getText().toString();
			if (CommonUtility.isNull(money)) {
				CommonUtility.tip(this, "请输入充值金额");
				return;
			}
			btn_pay_wechat.setEnabled(false);
			setUIEnabled(false);
			AccountRechargeApplyRequest req = new AccountRechargeApplyRequest();
			req.Pay_Platform = GlobalSettings.PAY_PLATFORM_WEIXIN;
			req.cost = Double.parseDouble(money);
			req.token = GlobalSettings.sToken;
			req.spbill_create_ip = DeviceUtility.DeviceInfo.getLocalHostIp();
			AccountRechargeApplyTask task = new AccountRechargeApplyTask();
			task.setRequest(req);
			task.addListener(new NetTaskListener<AccountRechargeApplyTask.AccountRechargeApplyRequest, AccountRechargeApplyTask.AccountRechargeApplyResponse>() {

				@Override
				public void onException(
						INetTask<AccountRechargeApplyRequest, AccountRechargeApplyResponse> task,
						Exception e) {
					btn_pay_wechat.setEnabled(true);
				}

				@Override
				public void onComplete(
						INetTask<AccountRechargeApplyRequest, AccountRechargeApplyResponse> task,
						AccountRechargeApplyResponse response) {
					btn_pay_wechat.setEnabled(true);
					if (response.ResultCode != 200) {
						return;
					}
					try {
						JSONObject object = new JSONObject(JsonUtil
								.convert(response.Res.WeiXinXMLRes));
						if (!CommonUtility.isNull(object)
								&& object.getString("return_code").equals(
										"SUCCESS")) {
							IWXAPI api = WXAPIFactory.createWXAPI(getContext(),
									ShareWXUtils.APP_ID, false);
							boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
							if (isPaySupported) {
								PayReq req = new PayReq();
								req.appId = ShareWXUtils.APP_ID;
								req.partnerId = object.getString("partnerId");
								req.prepayId = object.getString("prepayId");
								req.nonceStr = object.getString("nonceStr");
								req.timeStamp = object.getString("timeStamp");
								req.packageValue = object
										.getString("packageValue");
								req.sign = object.getString("sign");
								api.sendReq(req);
							} else {
								toast("您当前微信版本不支持支付功能，请下载最新版本进行更新");
							}
						} else {
							toast("支付请求失败");
						}
					} catch (Exception e) {
						e.printStackTrace();
						toast("支付请求失败");
					}
				}
			});
			add(task);
		} else if (id == R.id.btn_pay_ali) {
			String money = edit_money.getText().toString();
			if (CommonUtility.isNull(money)) {
				CommonUtility.tip(this, "请输入充值金额");
				return;
			}
			setUIEnabled(false);
			AccountRechargeApplyRequest req = new AccountRechargeApplyRequest();
			req.Pay_Platform = GlobalSettings.PAY_PLATFORM_ALI;
			req.cost = Double.parseDouble(money);
			req.token = GlobalSettings.sToken;
			req.spbill_create_ip = DeviceUtility.DeviceInfo.getLocalHostIp();
			AccountRechargeApplyTask task = new AccountRechargeApplyTask();
			task.setRequest(req);
			task.addListener(new NetTaskListener<AccountRechargeApplyTask.AccountRechargeApplyRequest, AccountRechargeApplyTask.AccountRechargeApplyResponse>() {

				@Override
				public void onException(
						INetTask<AccountRechargeApplyRequest, AccountRechargeApplyResponse> task,
						Exception e) {
					setUIEnabled(true);
				}

				@Override
				public void onComplete(
						INetTask<AccountRechargeApplyRequest, AccountRechargeApplyResponse> task,
						AccountRechargeApplyResponse response) {
					if (response.ResultCode != 200) {
						setUIEnabled(true);
						return;
					}
					doAliPay(response.Res.Order.OrderID);
				}
			});
			add(task);
		}
	}

	protected void doAliPay(String outTradeNo) {
		AlipayTask task = new AlipayTask();
		task.setContext(this);
		task.setPartner(GlobalSettings.ALI_PAY_PARTNER);
		task.setSeller(GlobalSettings.ALI_PAY_SELLER);
		task.setRsaPrivate(GlobalSettings.ALI_PAY_PRIVATE_KEY);
		task.setOutTradeNo(outTradeNo);
		task.setSubject("皮肤科医生");
		task.setBody("皮肤科医生");
		task.setTotalFee(edit_money.getText().toString());
		task.setNotifyUrl(GlobalSettings.ALI_PAY_NOTIFY_URL);
		task.addListener(new AlipayListener() {

			@Override
			public void onStop(AlipayTask task) {

			}

			@Override
			public void onStart(AlipayTask task) {

			}

			@Override
			public void onException(AlipayTask task, Exception e) {
				OAlert alert = new OAlert(getContext());
				alert.setCancelable(false);
				alert.setOK("确认");
				alert.setTitle("支付失败");
				alert.setListener(new OAlert.OAlertListener() {

					@Override
					public boolean onDismiss(OAlert alert) {
						finish();
						return false;
					}

					@Override
					public boolean onOK(OAlert alert) {
						return false;
					}

					@Override
					public boolean onCancel(OAlert alert) {
						return false;
					}
				});
				alert.show();
				setUIEnabled(true);
			}

			@Override
			public void onComplete(AlipayTask task) {
				Intent data = new Intent(Constant.RECEIVER_ACCOUNT_CHONGZHI);
				sendBroadcast(data);
				OAlert alert = new OAlert(getContext());
				alert.setCancelable(false);
				alert.setOK("确认");
				alert.setTitle("支付成功");
				alert.setListener(new OAlert.OAlertListener() {

					@Override
					public boolean onDismiss(OAlert alert) {
						finish();
						return false;
					}

					@Override
					public boolean onOK(OAlert alert) {
						return false;
					}

					@Override
					public boolean onCancel(OAlert alert) {
						return false;
					}
				});
				alert.show();
				setUIEnabled(true);
			}
		});
		task.start();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		CODE = -100001;
	}

	/*@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}*/
	
}
